package br.siseventos.service;

import br.siseventos.model.TbUsuario;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("authenticationService")
public class AuthenticationService extends HibernateDaoSupport implements UserDetailsService, Serializable {

    @Autowired
    public AuthenticationService(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }

    @SuppressWarnings("unchecked")
    @Override
    public UserDetails loadUserByUsername(String login) {
        Session sessao = null;
        Transaction t = null;
        List resultado = null;
        try {
            sessao = getSession();
            t = sessao.beginTransaction();
            Criteria criteria = sessao.createCriteria(TbUsuario.class);
            criteria.add(Restrictions.eq("usr_usuario", login));
            resultado = criteria.list();
            if (resultado != null && resultado.isEmpty()) {
                throw new UsernameNotFoundException("Usuário não encontrado!");
            }
            
            t.commit();
        } catch (Exception e) {
            if(t != null){
                try {
                    t.rollback();
                } catch (Exception ex) {
                }
            }
        }finally{
            
        }
        return (resultado.get(0) != null) ? new UserAdapter((TbUsuario) resultado.get(0)) : null;
    }
}
